package io.github.wslxm.springbootplus2.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.github.wslxm.springbootplus2.core.enums.BaseDic;
import io.github.wslxm.springbootplus2.core.utils.XjPropUtil;
import io.github.wslxm.springbootplus2.core.utils.bean.XjSpringContextUtil;
import io.github.wslxm.springbootplus2.manage.sys.handle.InitSuperManageAuthHandle;
import io.github.wslxm.springbootplus2.manage.sys.model.entity.SysAuthority;
import io.github.wslxm.springbootplus2.manage.sys.service.SysAuthorityService;
import io.github.wslxm.springbootplus2.manage.sys.service.SysRoleService;
import io.github.wslxm.springbootplus2.starter.redis.config.next.CacheThreadLocal;
import io.github.wslxm.springbootplus2.utils.XjAuthCacheKeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 项目完全启动成功后的执行的一些处理操作
 *
 * @author wangsong
 * @version 1.0.1
 * @mail 1720696548@qq.com
 * @date 2020/7/23 0023 9:04
 */
@Component
@Slf4j
public class InitCommandLineRunner implements CommandLineRunner {

    @Autowired
    private SysAuthorityService adminAuthorityService;

    @Autowired
    private InitSuperManageAuthHandle initSuperManageAuthHandle;

    @Autowired
    private SysRoleService sysRoleService;

    @Override
    public void run(String... args) {
        CacheThreadLocal.setPrefix("init");
        // ========== 启动信息配置参数打印 ========
        // 启动成功图
        getSuccessYellowBright();
        // 更新权限表数据
        adminAuthorityService.refreshAuthAll();
        // 更新超管角色权限
        initSuperManageAuthHandle.run();
        // 打印
        this.authPrint();
        // 当前启动环境
        log.info("当前启动环境 spring.profiles.active = {}", XjSpringContextUtil.getActiveProfile());
        log.info("当前启动端口 server.port = {}", XjPropUtil.findByKey("server.port"));
        // 日志测试
        log.info("开始测试当前日志级别配置【error-错误日志 | warn-警告日志 | info-普通日志 | debug-调试日志】 最后输出的日志类型为当前日志级别");
        log.error("error 错误日志已正常输出");
        log.warn("warn 警告日志已正常输出");
        log.info("info 普通日志已正常输出");
        log.debug("debug 调试日志已正常输出");
        CacheThreadLocal.remove();
    }

    /**
     * 启动成功图
     */
    public static void getSuccessYellowBright() {
        log.info("\r\n" +
                "         ####                #             #  ##               ##  \r\n" +
                "     #########        ##### ##             #               #   ##  \r\n" +
                "      ##   ##        ####   #####          ####        ######  # ##\r\n" +
                "      #    ##            #########    #######          ############\r\n" +
                "     ########       ####### ## ##     ###   #  #         ## ####  #\r\n" +
                "     ##            #####    #  ##      #    ## ##        ##   ##  #\r\n" +
                "     ##               # #  ##  ##      # ### ###         ###  #   #\r\n" +
                "     ##########      ##### ##  ##      ## ## ###       ####  ##  ##\r\n" +
                "    ## ###  ###     #### ###   #      ##  ## ##       ###   ##   ##\r\n" +
                "    ## ##   ##      ##    ##  ##      ##  # ####            ##   ##\r\n" +
                "   ##  ##  ##            ## ####     ##  ## #  ## #        ##  ### \r\n" +
                "  ##   #######          ##   ##      #   #      ###       #    ### \r\n" +
                "                             #                   ##                ");
    }



    public void authPrint() {
        List<SysAuthority> authorityList = adminAuthorityService.list(new LambdaQueryWrapper<SysAuthority>()
                .orderByDesc(SysAuthority::getType)
                .orderByDesc(SysAuthority::getMethod)
        );
        Map<String, SysAuthority> listAllToMap = authorityList.stream().collect(Collectors.toMap(p -> XjAuthCacheKeyUtil.get(p.getMethod(), p.getUrl()), auth -> auth));
        // 数据统计
        int authorityCount = 0;
        int authorityCountState0 = 0;
        int authorityCountState1 = 0;
        for (SysAuthority auth : listAllToMap.values()) {
            // 所有被管理的权限,管理端，需登录/授权的接口数量
            // 需登录接口数量
            if (StringUtils.isNotBlank(auth.getPid()) && auth.getState().equals(BaseDic.AuthorityState.V1.getValue())) {
                authorityCountState1++;
            }
            // 放行接口数量
            if (StringUtils.isNotBlank(auth.getPid()) && auth.getState().equals(BaseDic.AuthorityState.V0.getValue())) {
                authorityCountState0++;
            }
            // 总接口数
            if (StringUtils.isNotBlank(auth.getPid())) {
                authorityCount++;
            }
        }
        log.info("权限数据加载成功, 当前 [无需登录] 的接口数量为: {} ", authorityCountState0);
        log.info("权限数据加载成功, 当前 [需登录] 的接口数量为: {}", authorityCountState1);
        log.info("权限数据加载成功, 当前 [所有接口] 的接口数量为: {}", authorityCount);
    }
}